package com.example.rk.controller;

import ch.qos.logback.classic.Logger;
import com.example.rk.common.MyPageInfo;
import com.example.rk.common.SessionParameter;
import com.example.rk.entity.Admin;

import com.example.rk.service.AdminService;
import com.google.code.kaptcha.Constants;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    public  static  final String FILE_STORE_PATH="D:/A/shuju/rk/src/main/resources/static/style/images/upload";
    @Autowired
    private AdminService adminService;
    @RequestMapping("/show")
    @ResponseBody
    public String show() {
        return "hello springboot";
    }

    @RequestMapping("/doRegister")
    @ResponseBody
    public String doRegister(Admin admin) {
        String a="学生";
        String b=admin.getName();
        String c=admin.getPwd();
        admin.setType(a);
        return adminService.doRegister(admin);
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public String doLogin(Admin admin, HttpSession session) {

        return adminService.doLogin(admin, session);

    }

    @RequestMapping("/main")
    public ModelAndView main(HttpServletRequest request, ModelAndView mv) {
        Admin admin1 = (Admin) request.getSession().getAttribute(SessionParameter.ADMIN_INFO);
        Admin admin=adminService.getAdmin(admin1.getId());
        mv.addObject("admin", admin);
        if (admin.getType().equals("管理员")) {
            mv.setViewName("/gly/main");
            return mv;
        } else if (admin.getType().equals("学生")) {
            mv.setViewName("/xs/main");
            return mv;
        }else if(admin.getType().equals("公司"))
        {
            mv.setViewName("/gs/main");
            return mv;
        }else
      {
          mv.setViewName("/renko/list");
          return mv;
       }

}

    @RequestMapping("/list")
    public ModelAndView main1(HttpServletRequest request, ModelAndView mv) {
        mv.setViewName("/gly/adminlist");
        MyPageInfo myPageInfo = adminService.findBySearch(request);
        //List<RenKo> courseList= renKoService.findAll();
        mv.addObject("searchname", request.getParameter("name"));
        mv.addObject("searchtype", request.getParameter("type"));
        mv.addObject("pageInfo", myPageInfo);
        return mv;
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") int id) {
        adminService.deleteById(id);
        return "redirect:/admin/list";
    }

    @RequestMapping("/doAdd")
    @ResponseBody
    public String doAdd(Admin admin) {
        return adminService.doAdd(admin);
    }

    @RequestMapping("/openEdit/{id}")
    public ModelAndView openEdit(@PathVariable("id") int id, ModelAndView mv) {
        Admin admin = adminService.findById(id);
        mv.setViewName("/gly/edit");
        mv.addObject("admin", admin);
        return mv;
    }

    @RequestMapping("/doEdit")
    @ResponseBody
    public String doEdit(HttpServletRequest request,Admin admin) {
        return adminService.doEdit(admin);
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();  //设置session失效
        return "redirect:/jsp/admin/login.jsp";  //重定向到登录页面
    }
    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(@RequestPart(name = "file", required = false) MultipartFile multipartFile,
                             HttpServletRequest request){
        Admin admin = (Admin)request.getSession().getAttribute(SessionParameter.ADMIN_INFO);
        String oldName = multipartFile.getOriginalFilename();  // aaabbb.jpg    12_2022-08-15.jpg
        String substring = oldName.substring(oldName.indexOf("."));  //.jpg
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(new Date());
        if(admin.getImageUrl()!=""){
            try {
                String filePath ="D:\\A\\shuju\\rk\\src\\main\\resources\\static\\style\\images\\upload\\"+ admin.getImageUrl();
                filePath = filePath.toString();
                java.io.File myDelFile = new java.io.File(filePath);
              boolean a=myDelFile.delete();
              int c=11;
            } catch (Exception e) {
                System.out.println("删除文件操作出错");
                e.printStackTrace();
            }
        }
        //构建真实的文件路径
        File fileStoePAth = new File(FILE_STORE_PATH);
        try {
            if (!fileStoePAth.exists())
                fileStoePAth.mkdirs() ;  //如果存储路径不存在，就创建
            File newFile = new File(FILE_STORE_PATH+ File.separator+admin.getId()+"-"+admin.getName()+"-"+substring);
            multipartFile.transferTo(newFile);
          adminService.setImageUrl(newFile.getName(),admin.getId());
        } catch (IOException e) {
            return "error";
        }
        return "ok";
    }

//    @GetMapping("/kaptcha")
//    public void getKaptcha(HttpServletResponse response, HttpSession session) {
//        //生成验证码
//        Producer kaptchaProducer = null;
//        String text = kaptchaProducer.createText();
//        BufferedImage image = kaptchaProducer.createImage(text);
//
//        //将验证码存入session
//        session.setAttribute("kaptcha", image);
//
//        //将图片传给浏览器
//        response.setContentType("image/png");
//        try {
//            OutputStream os = response.getOutputStream();
//            ImageIO.write(image, "PNG", os);
//        } catch (IOException e) {
//            Logger logger = null;
//            logger.error("图片输出错误" + e.getMessage());
//        }
//    }

}



